package com.myamap.tool;

import java.io.IOException;
import java.util.HashMap;

import org.CrossApp.lib.CrossAppActivity;
import org.CrossApp.lib.CrossAppHelper;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.maps2d.AMap.OnInfoWindowClickListener;
import com.amap.api.maps2d.AMap.OnMarkerClickListener;
import com.amap.api.maps2d.AMap.OnMarkerDragListener;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.AMap.OnMapClickListener;
import com.amap.api.maps2d.AMap.OnMapLoadedListener;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.d6td.test.R;

import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;

/*
 * 高德2D地图包装类
 * 
 */
public class MyAmapView implements OnMapLoadedListener, OnMapClickListener, OnMarkerDragListener, OnMarkerClickListener, OnInfoWindowClickListener, AMapLocationListener
{
	private MapView mAmapView;
	private int viewTag;
	
	private double mdLat;
	private double mdLng;
	
	private boolean mbAmapLoaded;
	
	private boolean mbLoc;
	
	private static Button mLocationBt;
	
	private AMapLocationClient mLocationClient;
	
	private Marker mLocMarker;
	
	private HashMap<String, Marker> s_Markers = new HashMap<String, Marker>();
	
	public MyAmapView(Context context, int viewTag, Bundle bundle) 
	{
    	mdLat = 39.9;
    	mdLng = 116.3;
    	mbAmapLoaded = false;
    	mbLoc = false;
    	
		mAmapView = new MapView(CrossAppActivity.getContext());
		mAmapView.onCreate(bundle);
		mAmapView.setVisibility(View.GONE);
    	CrossAppActivity.getFrameLayout().addView(mAmapView);
    	
    	initListener();
    	
    	initLocation();
	}
	
	private void initListener()
	{
    	//加载完成回调
    	mAmapView.getMap().setOnMapLoadedListener(this);
		//点击地图回调
    	mAmapView.getMap().setOnMapClickListener(this);
    	//marker拖拽回调
    	mAmapView.getMap().setOnMarkerDragListener(this);
    	//marker拖拽回调
    	mAmapView.getMap().setOnMarkerClickListener(this);
    	//marker拖拽回调
    	mAmapView.getMap().setOnInfoWindowClickListener(this);
	}
	
	private void initLocation()
	{
		//Location Marker
		MarkerOptions markeroption = new MarkerOptions();
		markeroption.draggable(false);
		markeroption.title("我的位置");		
		markeroption.icon(BitmapDescriptorFactory.fromResource(R.drawable.green_imv));
		mLocMarker = mAmapView.getMap().addMarker(markeroption);
		
		//location
    	mLocationClient = new AMapLocationClient(CrossAppActivity.getContext());
		AMapLocationClientOption locationOption = new AMapLocationClientOption();
		locationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
		locationOption.setOnceLocation(true);
		locationOption.setNeedAddress(true);
		mLocationClient.setLocationOption(locationOption);
		mLocationClient.setLocationListener(this);
    	
    	mLocationBt = new Button(CrossAppActivity.getContext());
    	mLocationBt.setBackgroundResource(R.drawable.location_selected2d);
        mLocationBt.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
            	if (mLocationClient != null)
            	{
            		mLocationClient.startLocation();
            	}
            }
        });
        mAmapView.addView(mLocationBt);
	}
	
	public void destroy()
	{
		if (mLocMarker != null)
		{
			mLocMarker.remove();
			mLocMarker.destroy();
		}
		
		if (mLocationClient != null)
    	{
			mLocationClient.stopLocation();
			mLocationClient.onDestroy();
			mLocationClient = null;
		}
		
		CrossAppActivity.getFrameLayout().removeView(mAmapView);
		clearMarkers();
		mAmapView.removeAllViews();
		mAmapView.getMap().clear();
		mAmapView.onDestroy();
	}
	
	public void setVisible(boolean visible)
	{
		mAmapView.setVisibility(visible ? View.VISIBLE : View.GONE);
	}
	
	public void setMapCenter(double lat, double lng)
	{
		mbLoc = false;
		
		mdLat = lat;
		mdLng = lng;
		
		if (mbAmapLoaded)
		{
			if (mAmapView.getMap() != null)
    		{         
    			mAmapView.getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mdLat, mdLng), mAmapView.getMap().getCameraPosition().zoom));
    		}
		}
	}
	
	public void startLocation()
	{
		if (mLocationClient != null)
    	{
			mbLoc = true;
    		mLocationClient.startLocation();
    	}
	}
	
	public void setMapZoomLevel(float level)
	{
		if (mAmapView.getMap() != null)
		{
			mAmapView.getMap().moveCamera(CameraUpdateFactory.zoomTo(level));
		}
	}
	
	public void setAMapRect(int x, int y, int width, int height)
	{
		if (mAmapView.getVisibility() != View.VISIBLE)
		{
			mAmapView.setVisibility(View.VISIBLE);
		}
		
		FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        layoutParams.gravity = Gravity.LEFT|Gravity.TOP;
        layoutParams.leftMargin = x;
        layoutParams.topMargin = y;
        layoutParams.width = width;
        layoutParams.height = height;
        mAmapView.setLayoutParams(layoutParams);
        
        FrameLayout.LayoutParams locbtParams = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.WRAP_CONTENT,
                FrameLayout.LayoutParams.WRAP_CONTENT);
		
		locbtParams.gravity = Gravity.LEFT|Gravity.TOP;
		locbtParams.leftMargin = (int) (width - 80 * (CrossAppHelper.getDPI() / 320) - 20);
		locbtParams.topMargin = 20;
		locbtParams.width = (int) (80 * (CrossAppHelper.getDPI() / 320));
		locbtParams.height = (int) (80 * (CrossAppHelper.getDPI() / 320));
		
		mLocationBt.setLayoutParams(locbtParams);
	}
	
	public void addMarker(String marktag, String img, boolean dragable, String title, String content, double lat, double lng)
	{
		MarkerOptions markeroption = new MarkerOptions();
		markeroption.draggable(dragable);
		markeroption.title(title);
		markeroption.snippet(content);
		markeroption.position(new LatLng(lat, lng));
		if (img != null && img != "")
		{
			try
			{
				if (CrossAppActivity.getContext().getAssets().open(img) != null)
				{
					markeroption.icon(BitmapDescriptorFactory.fromAsset(img));
				}
			} 
			catch (IOException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
				markeroption.icon(BitmapDescriptorFactory.fromResource(R.drawable.green_imv));
			}
		}
		else
		{
			markeroption.icon(BitmapDescriptorFactory.fromResource(R.drawable.green_imv));
		}
		
		Marker marker = mAmapView.getMap().addMarker(markeroption);
		
    	s_Markers.put(marktag, marker);
	}
	
	public void deleteMarker(String marktag)
	{
		Marker marker = s_Markers.get(marktag);
		if (marker != null)
		{
			s_Markers.remove(marktag);
			if (marker.isInfoWindowShown())
			{
				marker.hideInfoWindow();
			}
			marker.remove();
			marker.destroy();
		}
	}
	
	public void clearMarkers()
	{
		for (String key1:s_Markers.keySet())
		{
			Marker marker = s_Markers.get(key1);
			if (marker != null)
			{
				if (marker.isInfoWindowShown())
				{
					marker.hideInfoWindow();
				}
				marker.remove();
				marker.destroy();
			}
		}
		
		s_Markers.clear();
	}
	
	//OnMapClickListener
	@Override
	public void onMapClick(LatLng arg0) 
	{
		// TODO Auto-generated method stub
		MyAmapViewHelper.onAmapClicked(viewTag, arg0.latitude, arg0.longitude);
	}

	//OnMapLoadedListener
	@Override
	public void onMapLoaded()
	{
		// TODO Auto-generated method stub
		mbAmapLoaded = true;
		MyAmapViewHelper.onAmapLoaded(viewTag);

		if (mAmapView.getMap() != null)
		{
			if (mbLoc)
			{
				mLocMarker.setPosition(new LatLng(mdLat, mdLng));
			}
			
			mAmapView.getMap().moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(mdLat, mdLng)));
		}
	}

	//OnMarkerDragListener
	@Override
	public void onMarkerDrag(Marker arg0)
	{
		// TODO Auto-generated method stub
		String key = null;
		for (String key1:s_Markers.keySet())
		{
			if (s_Markers.get(key1).equals(arg0))
			{
				key = key1;
				break;
			}
		}
		if (key != null)
		{
			MyAmapViewHelper.onAmapMarkerDrag(viewTag, key, arg0.getPosition().latitude, arg0.getPosition().longitude);
		}
	}

	//OnMarkerDragListener
	@Override
	public void onMarkerDragEnd(Marker arg0)
	{		
		// TODO Auto-generated method stub
		String key = null;
		for (String key1:s_Markers.keySet())
		{
			if (s_Markers.get(key1).equals(arg0))
			{
				key = key1;
				break;
			}
		}
		if (key != null)
		{
			MyAmapViewHelper.onAmapMarkerDragEnd(viewTag, key, arg0.getPosition().latitude, arg0.getPosition().longitude);
		}
	}

	//OnMarkerDragListener
	@Override
	public void onMarkerDragStart(Marker arg0) 
	{
		// TODO Auto-generated method stub
		String key = null;
		for (String key1:s_Markers.keySet())
		{
			if (s_Markers.get(key1).equals(arg0))
			{
				key = key1;
				break;
			}
		}
		if (key != null)
		{
			MyAmapViewHelper.onAmapMarkerDragStart(viewTag, key, arg0.getPosition().latitude, arg0.getPosition().longitude);
		}
	}

	//OnMarkerClickListener
	@Override
	public boolean onMarkerClick(Marker arg0) 
	{
		String key = null;
		for (String key1:s_Markers.keySet())
		{
			if (s_Markers.get(key1).equals(arg0))
			{
				key = key1;
				break;
			}
		}
		if (key != null)
		{
			MyAmapViewHelper.onAmapMarkerClick(viewTag, key);
		}
		return false;
	}

	//OnInfoWindowClickListener
	@Override
	public void onInfoWindowClick(Marker arg0)
	{
		// TODO Auto-generated method stub
		String key = null;
		for (String key1:s_Markers.keySet())
		{
			if (s_Markers.get(key1).equals(arg0))
			{
				key = key1;
				break;
			}
		}
		if (key != null)
		{
			MyAmapViewHelper.onAmapMarkerInfoWindowClick(viewTag, key);
		}
	}

	//OnLocationChangedListener
	@Override
	public void onLocationChanged(AMapLocation location) 
	{
		// TODO Auto-generated method stub
		int code = 0;
		double lat = 0.0;
		double lng = 0.0;
		String formatAddr = ""; 
		String province = ""; 
		String city = "";
		String district = "";
		String street = ""; 
		String number = "";
		String poi = ""; 
		String adcode = "";
		if (location != null && location.getErrorCode() == 0) 
		{
			code = 0;
			lat = location.getLatitude();
			lng = location.getLongitude();
			
			mdLat = lat;
			mdLng = lng;
			
			formatAddr = location.getAddress(); 
			province = location.getProvince(); 
			city = location.getCity();
			district = location.getDistrict();
			street = location.getStreet(); 
			number = location.getStreetNum();
			poi = location.getPoiName(); 
			adcode = location.getAdCode();

			mLocMarker.setPosition(new LatLng(lat, lng));
			mLocMarker.setTitle(formatAddr);
			mLocMarker.showInfoWindow();
			mAmapView.getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 16.0f));
		}
		else 
		{
			code = -2;
		}
		
		mLocationClient.stopLocation();
		
		MyAmapViewHelper.onAmapLocationEnd(viewTag, code, lat, lng, formatAddr, province, city, district, street, number, poi, adcode);
	}
}
